package com.hfzy.ihk.web.websocket.serviceImpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.facade.websocket.linkcall.service.WebSocketService;
import com.hfzy.ihk.web.websocket.constant.Constants;
import com.hfzy.ihk.web.websocket.support.SampleCache;
import com.hfzy.ihk.web.websocket.support.WebSocketManager;
import com.hfzy.ihk.web.websocket.support.annotation.RePushDataToChrome;
import com.hfzy.ihk.web.websocket.utils.SpringWebSocketUtils;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/22.
 *
 * @author wws
 */
@Service(version = "1.0.0")
public class WebSocketServiceImpl implements WebSocketService {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(WebSocketServiceImpl.class);

    /**
     * 广播给某个User
     * */
    @Override
    public boolean pushToBrowserByUserId(String userId, String json) {

        if(StringUtil.isEmpty(userId))
            return false;

        Map<String,List<WebSocketSession>> machineWebSocketListMap  = WebSocketManager.getBrowserUserMahineWebSocketSessionsMap().get(userId);

        if(machineWebSocketListMap!=null && machineWebSocketListMap.size()>0){

            for(Map.Entry<String,List<WebSocketSession>> entry:machineWebSocketListMap.entrySet()){

                if(entry.getValue()!=null&&entry.getValue().size()>0){

                    for(WebSocketSession webSocketSession:entry.getValue()){

                        if(webSocketSession.isOpen()){
                            SpringWebSocketUtils.pushToClient(webSocketSession,json);
                        }

                    }
                }
            }

        }

        return true;
    }

    @Override
    public boolean pushToBrowserByUserId4ChromePlugin(String userId, String json) {

        if(StringUtil.isEmpty(userId)) {
            return false;
        }
        WebSocketSession webSocketSession = WebSocketManager.browserUserWebSocketSession4ChromePluginMap.get(userId);

        if(webSocketSession == null){
            logger.info("maybe plugin's webSocketSession has closed! userId:{},json:{}",userId,json);
            return false;
        }

        if(webSocketSession.isOpen()){
            String res = SpringWebSocketUtils.pushToClient(webSocketSession,json);
            return Constants.SUCCESS.equals(res);
        }

        logger.error("webSocketSession is close,userId:{},json:{}",userId,json);

        return false;
    }

    @Override
    public  boolean pushToBrowserBySessionId(String sessionId, String json){

        logger.info("pushToBrowserBySessionId：{},jsonStr:{}",sessionId,json);

        String token = SampleCache.sessionIdTokenMap.get(sessionId);
        return pushToBrowserByToken(token,json);
    }

    /**
     * 线上运行时关机重启，会影响后续分析内容的推送
     * */
    @Override
    @RePushDataToChrome(tryTimes=1,timeOut=500,type="token")
    public boolean pushToBrowserByToken(String token, String json) {

        if(StringUtil.isEmpty(token)) {
            return false;
        }

        WebSocketSession webSocketSession = WebSocketManager.browserTokenWebSocketSessionMap.get(token);
        if(webSocketSession == null){
            logger.info("maybe browser's webSocketSession has closed! token:{}",token);
            return false;
        }

        if(webSocketSession.isOpen()){
            String res = SpringWebSocketUtils.pushToClient(webSocketSession,json);
            if(Constants.SUCCESS.equals(res)){
                logger.info("pushToBrowserByToken:{}",json);
                return true;
            }else {
                return false;
            }
        }
        logger.error("webSocketSession is close,token:{},json:{}",token,json);
        return false;
    }

    @Override
    public boolean pushToAppByUserId(String userId, String json,String isTest) {

        if(StringUtil.isEmpty(userId)) {
            return false;
        }
        //使用MAC来连接webSocket,非正式环境要转换
//        userId = WebSocketManager.tansUserId2PhoneMac(userId);
        if(Constants.TRUE.equals(isTest)){
            userId = WebSocketManager.createTestUserId(userId);
            logger.info("1 is test,userId:{}",userId);
        }

        WebSocketSession webSocketSession = WebSocketManager.appUserIdOrMacWebSocketSessionMap.get(userId);

        if(webSocketSession == null){
            logger.info("maybe app's webSocketSession has closed! userId:{}",userId);
            return false;
        }

        if(webSocketSession.isOpen()){
            String res = SpringWebSocketUtils.pushToClient(webSocketSession,json);
            if(Constants.SUCCESS.equals(res)){
                logger.debug("pushToAppByUserId 2 param:{}",json);
                return true;
            }else {
                return false;
            }

        }

        logger.error("webSocketSession is close,token:{},json:{}",userId,json);

        return false;
    }



    /**
     * 该方法仅发送call任务时调
     * */
    @Override
    public boolean pushToAppByUserId(String userId, String toAppJson, String cacheJson,String isTest) {

        if(StringUtil.isEmpty(userId))
            return false;

        //使用MAC来连接webSocket,非正式环境要转换
//        userId = WebSocketManager.tansUserId2PhoneMac(userId);

        if(Constants.TRUE.equals(isTest)){
            userId = WebSocketManager.createTestUserId(userId);
            logger.info("2 is test,userId:{}",userId);
        }

        WebSocketSession webSocketSession = WebSocketManager.appUserIdOrMacWebSocketSessionMap.get(userId);

        if(webSocketSession == null){
            logger.info("maybe app's webSocketSession has closed! userId:{}",userId);
            return false;
        }

        if(webSocketSession.isOpen()){


            String res = SpringWebSocketUtils.pushToClient(webSocketSession,toAppJson);
            if(Constants.SUCCESS.equals(res)){
                webSocketSession.getAttributes().put("currentCallBrowserSocketInfo",cacheJson);
                logger.debug("pushToAppByUserId 3 param:{}",toAppJson);
                return true;
            }else {
                return false;
            }

        }

        logger.error("webSocketSession is close,token:{},json:{}",userId,toAppJson);

        return false;
    }

    @Override
    public boolean pushToAppByToken(String token, String json) {
        return false;
    }

    @Override
    public boolean isFlagWebSocketChromePlugin(String userId) {

        if(StringUtil.isEmpty(userId))
            return false;

        WebSocketSession webSocketSession = WebSocketManager.browserUserWebSocketSession4ChromePluginMap.get(userId);

        if(webSocketSession == null){
            return false;
        }
        return true;
    }



    /**
    * //TODO
    * */
    @Override
    public String interruptAppCall(String sessionId, String userId, String targetCallPhone) {
        return "";
    }

    @Override
    public String closeAllAppConnetion() {

        int count=0;
        int success=0;
        boolean isNum=false;
        for(String userIdOrMac:WebSocketManager.appUserIdOrMacWebSocketSessionMap.keySet()){

            if(StringUtil.isNumeric(userIdOrMac))
                isNum=true;
            if(isNum)
                count++;
            WebSocketSession webSocketSession = WebSocketManager.appUserIdOrMacWebSocketSessionMap.get(userIdOrMac);

            if(webSocketSession == null){
                continue;
            }

            if(webSocketSession.isOpen()){
                try {
                    webSocketSession.close();
                    if(isNum)
                        success++;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return StringUtil.strConnect(Constants.SUCCESS_STR,"count:",String.valueOf(count),"success:",String.valueOf(success));
    }

    /**
     *
     * 通过serverId 推送到设备
     * @param serverId
     * @param data
     * @return
     */
    public boolean pushToSwxByServerId(String serverId,String data){
        try {
            if (serverId == null)
                return false;
            WebSocketSession webSocketSession = WebSocketManager.swxServerIdWebSocketSessionMap.get(serverId);
            if (webSocketSession == null)
                return false;
            SpringWebSocketUtils.pushToClient(webSocketSession, data);
            return true;

        }catch (Exception e){
            logger.error("推送数据到设备异常data：{}",data,e);
            return false;
        }
    }

}
